import { _decorator, AudioClip, AudioSource, Camera, clamp, Component, Label, Layers, log, Node, Prefab, randomRange, randomRangeInt, resources, Sprite, SpriteFrame, tween, UIOpacity, UITransform, v3, Vec3, view, warn, math } from 'cc';
import { Player } from '../Player/Player';
import { Battle } from '../Battle';
import { Enum_AudioClip } from '../Enum';
import { ResourcesUtil } from '../ResourcesUtil';
import { Globals } from '../Globals';
import { EnEvent } from '../Common/const/EnEvent';
import { GameAPI } from '../Common/GameAPI';
import { EnemyController } from '../Logic/Enemy/EnemyController';
const { ccclass, property } = _decorator;

@ccclass('Main')
export class Main extends Component {
    @property(Node) playerNode: Node = null; // 玩家节点
    @property(Node) joyStickNode: Node = null; // 摇杆节点
    @property(Node) Map: Node = null;  // 地图节点
    @property(Node) LifebarNode: Node = null; // 生命条节点
    @property(Node) ExpBarNode: Node = null; // 经验条节点
    @property(Node) HeroSelectPanelNode: Node = null; // 英雄塔选择面板节点
    @property(Node) playerHeadNode: Node = null; // 技能选择面板节点
    @property(Node) TitlePanelNode: Node = null; // 提示面板
    @property(Node) GameOverPanelNode: Node = null; // 游戏结束面板
    @property(AudioSource) musicAudio: AudioSource; //控制背景music
    @property(AudioSource) enemyAudio: AudioSource; //控制敌人叫声
    @property(Node) enemyParent: Node;
    @property(Node) energyObjParent: Node;
    @property(Node) contentNode: Node;
    @property(Node) downloadNode: Node;
    @property(Node) skillEffectParent: Node;
    @property(Node) polygonNav2D: Node;
    

    //创建敌人的间隔
    createEnemyTime = 1;
    //经验值
    exp = 0;
    //等级
    expLevel = 1;


    protected onLoad() {
        Battle.startGame = false;

        // 玩家节点保存到Battle中
        Battle.playerNode = this.playerNode.getChildByName("Player");
        // Battle.playerNode = this.playerNode;
        // 地图节点
        this.Map && (Battle.MapNode = this.Map);

        // 创建敌人 父节点
        // Battle.EnemyParent = this.createParentNode("EnemyParent");
        Battle.EnemyParent = this.enemyParent;
        Battle.EnergyObjParent = this.energyObjParent;
        Battle.SkillEffectParent = this.skillEffectParent;
        Battle.ContentParent = this.contentNode;
        Battle.PolygonNav2D = this.polygonNav2D;
        // 创建伤害数字 父节点
        Battle.DamageTextParent = this.createParentNode("DamageTextParent");
        // 创建player玩家子弹 父节点
        Battle.PlayerBulletParent = this.createParentNode("PlayerBulletParent");
        // let elementNode = this.node.getChildByName("ElementNode");
        // Battle.EnemyTree = elementNode.getChildByName("TreeNode");
        Battle.EnemyTree = this.enemyParent;
        Battle.IsFirstTree = false;

        GameAPI.RegGEvent(EnEvent.AddHeroEvent, this.OnAddHeroEvent.bind(this), this);
    }
    protected onDisable(): void {
    }
    onDestroy() {
        GameAPI.OffAllCaller(this);
    }

    OnAddHeroEvent() {
        this.HeroSelectPanelNode.active = true;
    }

    protected update(deltaTime: number) {
        // 创建敌人
        this.createEnemyTime -= deltaTime;
        if (Battle.startGame) {
            // 增加一批敌人
            let count = this.getEnemyNode();
            if (this.createEnemyTime <= 0 && count < 60) {
                this.createEnemy(Battle.createEnemyNum, 1);
                this.createEnemyTime = 1;
            }
        }
    }

    getEnemyNode() {
        let enemyCount = 0;
        for (let index = 0; index < Battle.EnemyParent.children.length; index++) {
            const element = Battle.EnemyParent.children[index];
            let nodeName = element.name;
            if (nodeName.includes("Enemy") || nodeName.includes("Boss")) {
                let enemyCom = element.getComponent(EnemyController);
                if (!enemyCom.isDie) {
                    enemyCount++;
                }
            }
        }
        return enemyCount;
    }

    /**
     * 监听生命条
     */
    listenLifeBar() {
        // 3.传递事件函数（把这里的函数到Player里面调用）player中的事件
        Battle.playerNode.getComponent(Player).onPlayerEvent((event: number, hurt: number) => {
            switch (event) {
                case Player.Event.HURT:
                    break;
                case Player.Event.CURE:
                    break;
                case Player.Event.DEAD:
                    // TODO: 游戏结束
                    this.GameOverPanelNode.active = true;
                    break;
                default:
                    break;
            }
        })
    }

    /**
         * 创建一个节点作为某个父节点
         * @param parentNodeName 此节点名称
         * @returns 此节点
         */
    createParentNode = (parentNodeName: string) => {
        const parentNode = new Node(parentNodeName); //创建节点
        parentNode.setParent(this.node); //添加到主节点下面
        parentNode.layer = Layers.Enum.UI_2D; //设置layer
        return parentNode;
    }

    /**
     * 创建敌人
     * @param oneEnemy 一次循环创建的最多有多少敌人，1-oneEnemy
     * @param oneEnemyTime 一次循环创建敌人的时间间隔
     */
    createEnemy(oneEnemy: number, oneEnemyTime: number) {
        // this.schedule(() => {
        // for (let i = 0; i < oneEnemyLimits; i++) {
        tween(this.node)
            .call(() => {
                const enemyNode = Globals.getNode("Enemy", Battle.EnemyParent);
                // 敌人位置范围值(敌人初始位置在相机外面，地图里面) - 800
                // 获取屏幕尺寸（相机尺寸） - 800
                const screenHeight = view.getVisibleSize().height;
                const screenWidth = view.getVisibleSize().width;
                // 相机的位置
                const cameraWorldPos = Battle.Camera.getWorldPosition();
                // 相机边界
                const left = cameraWorldPos.x - screenWidth / 2;
                const right = cameraWorldPos.x + screenWidth / 2;
                const top = cameraWorldPos.y + screenHeight / 2;
                const bottom = cameraWorldPos.y - screenHeight / 2;
                // 地图边界
                const MapNode = Battle.MapNode;
                const mapleft = MapNode.getWorldPosition().x - MapNode.getComponent(UITransform).contentSize.width / 2;
                const mapright = MapNode.getWorldPosition().x + MapNode.getComponent(UITransform).contentSize.width / 2;
                const maptop = MapNode.getWorldPosition().x + MapNode.getComponent(UITransform).contentSize.height / 2;
                const mapbottom = MapNode.getWorldPosition().x - MapNode.getComponent(UITransform).contentSize.height / 2;
                // 随机敌人在相机上下左右
                const direction = Math.floor(randomRange(0, 4)); //0，1，2，3
                //敌人位置
                let enemyPos = v3();
                const offset = 50; //偏移量，远离相机距离
                switch (direction) {
                    case 0: //上面
                        enemyPos.x = randomRange(left, right);
                        enemyPos.y = top + offset;
                        break;
                    case 1: //下面
                        enemyPos.x = randomRange(left, right);
                        enemyPos.y = bottom - offset;
                        break;
                    case 2: //左边
                        enemyPos.x = left - offset;
                        enemyPos.y = randomRange(top, bottom);
                        break;
                    case 3: //右边
                        enemyPos.x = right + offset;
                        enemyPos.y = randomRange(top, bottom);
                        break;
                }
                // 确保在地图内(Math.min 限制在不超过右边界，Math.max限制不超过左边界)
                enemyPos.x = Math.max(mapleft, Math.min(enemyPos.x, mapright));
                enemyPos.y = Math.max(mapbottom, Math.min(enemyPos.y, maptop));

                enemyNode.setWorldPosition(enemyPos);
                // enemyNode.getComponent(Enemy).speed = randomRange(.5, 1.5);
            })
            .delay(oneEnemyTime / oneEnemy)
            .union()
            .repeat(oneEnemy)
            .start();

        // }
        // }, deltaTime)
    }
}


